package com.p2p.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.p2p.common.enums.ResponseEnum;
import com.p2p.common.interceptor.databind.DataBind;
import com.p2p.common.interceptor.databind.DataBindManager;
import com.p2p.common.interceptor.databind.DataBindType;
import com.p2p.common.token.TokenService;
import com.p2p.common.utils.ResponseUtil;

/**
 * Created by lizhuolun on 2016/8/30. OAuth权限认证
 */
public class AccessInterceptor extends BaseInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AccessInterceptor.class);
    private static final DataBind<Long> UID_BIND = DataBindManager.getInstance().getDataBind(DataBindType.USER_ID);
    @Autowired
    private TokenService tokenService;


    @Override
    public boolean doPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        Long userId = tokenService.getKeyByToken(token);
        if (userId != null && userId > 0) {
            UID_BIND.put(userId);
            return true;
        } else {
            UID_BIND.put(null);
            ResponseUtil.write(request, response, ResponseEnum.TOKEN_INVALID.getCode(), ResponseEnum.TOKEN_INVALID.getMsg());
            logger.info("AccessInterceptor Token:{},userId:{}", token, userId);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UID_BIND.remove();
        super.afterCompletion(request, response, handler, ex);
    }

}
